﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using ParserGenerator.GrammarConstruction;

namespace ParserGenerator.ParserConstruction
{
    [Serializable]
    public sealed class ParserAutomatonAction : ReadOnlyCollection<ParserAutomatonContribution>
    {
        public ParserAutomatonState State { get; }
        public GrammarTerminalSymbol Token { get; }
        public ParserAutomatonShift Shift { get; private set; }
        public bool IsAmbiguous => Count > 1;

        internal ParserAutomatonAction(ParserAutomatonState state, GrammarTerminalSymbol token)
            : base(new List<ParserAutomatonContribution>())
        {
            if (state == null)
                throw new ArgumentNullException(nameof(state));
            if (token == null)
                throw new ArgumentNullException(nameof(token));
            State = state;
            Token = token;
        }

        internal void Add(ParserAutomatonContribution contribution)
        {
            if (contribution == null)
                throw new ArgumentNullException(nameof(contribution));
            if (contribution.IsShift)
            {
                if (Shift != null)
                {
                    string message = string.Format(SR.ShiftContributionSpecified, State, Token);
                    InvalidOperationException e = new InvalidOperationException(message);
                    throw e;
                }
                Shift = contribution.AsShift;
            }
            Items.Add(contribution);
        }
    }
}
